﻿using System.Globalization;
using Compiler.Entities;
using Core.AbstractEntities;

namespace Operations.Entities
{
    /// <summary>
    /// Execute operation for each item added in the stack
    /// </summary>
    public class OperationBinary : Operation
    {
        /// <summary>
        /// Constructor by default
        /// </summary>
        public OperationBinary(HpCollection hpCollection)
        {
            this.HpCollection = hpCollection;
        }

        /// <summary>
        /// Return the result of the operation
        /// 4   3  +  => 7
        /// 25  3  *  => 75
        /// 8   4  /  => 2
        /// </summary>
        public override HpElement Execute()
        {
            HpElement operatorItem = HpCollection.Get(HpCollection.Count - 1);
            HpElement element1 = HpCollection.Get(HpCollection.Count - 2);
            HpElement element2 = HpCollection.Get(HpCollection.Count - 3);


            string code = string.Format(new CultureInfo("en-US"), @"
            using System;
            public class Calculator
            {{
              public static object Execute()
              {{ 
               {0} o1 = {1};
               {2} o2 = {3};
               return o1{4}o2;
              }}
            }}",
            element1.Type.ToString(),
            element1.Value.ToString(),
            element2.Type.ToString(),
            element2.Value.ToString(),
            operatorItem.Value.ToString());

            object result = Program.Execute(code);

            HpElement newElement = new HpElement()
            {
                Type = result.GetType(),
                Value = result
            };

            return newElement;
        }
    }
}
